package com.jxchexie.signin;
import android.content.DialogInterface;
import android.content.Intent;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.utils.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jxchexie.adapter.MainPicAdapter;
import com.jxchexie.api.Api;
import com.jxchexie.app.App;
import com.jxchexie.model.HeadImage;
import com.jxchexie.model.ResponseLogin;
import com.jxchexie.model.SighInMessage;
import com.jxchexie.utils.Constant;
import com.jxchexie.utils.JsonUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Response;

import static com.jxchexie.api.Api.SIGNIN_MESSAGE;
import static com.jxchexie.api.Api.UPLOAD_HEAD;


public class MainActivity extends AppCompatActivity {
    private MaterialDialog md;
    private HeadImage hi;

    private int picwhich = 0; //保存单选按钮的选择
    private String uploadTemp;




    //定位
    private String Gprovince;
    private String Gcity;
    private String Gdistrict;
    private String location;
    //纬度
    public double Lat;
    //经度
    public double Lon;
    String strLon;
    String strLat;

    int currentMinute;

        //声明AMapLocationClient类对象
        public AMapLocationClient mLocationClient = null;
        //声明定位回调监听器
        public AMapLocationListener mLocationListener = new MyAMapLocationListener();
        //声明AMapLocationClientOption对象
        public AMapLocationClientOption mLocationOption = null;
        private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        //mLocationOption.setOnceLocationLatest(true);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);


        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }

    /**
     * 获取定位信息
     */
    private class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //此处获得成功，可以参照返回值表取需要的参数，我只要了省市县
                    location = aMapLocation.getAddress();
                    Gprovince = aMapLocation.getProvince();
                    Gcity = aMapLocation.getCity();
                    Gdistrict = aMapLocation.getDistrict();
                    Lat = aMapLocation.getLatitude();//获取纬度
                    Lon = aMapLocation.getLongitude();//获取经度

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }

    }


    private ArrayList<Integer> datas = new ArrayList<>();
    private MainPicAdapter adapter;
    private RecyclerView mRecycle;
    private ImageView mMap;


    private TextView actionA;
    private TextView actionB;
    private TextView actionC;
    private TextView actionD;
    private TextView actionE;
    private TextView mLocation;
    //主页
    private TextView actionHome;
    private CircleImageView bigPic;

    private ResponseLogin login;
    private TextView mUser_name;
    private TextView tv_signin;
    private Toolbar mainToolbar;

    private boolean quit = false; //设置退出标识

    public MainActivity() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
        setAdapter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getHead();
    }

    private void setAdapter() {
        LinearLayoutManager mLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
        mRecycle.setLayoutManager(mLayoutManager);
        //添加数据
        datas.add(R.drawable.z2);
        datas.add(R.drawable.z4);
        datas.add(R.drawable.z3);


        adapter=new MainPicAdapter(datas,MainActivity.this);
        PagerSnapHelper ps = new PagerSnapHelper();

        ps.attachToRecyclerView(mRecycle);
        mRecycle.setAdapter(adapter);
    }

    private void initView(){
        bigPic = findViewById(R.id.bigPic);
        mLocation = (TextView)findViewById(R.id.mLocation);

        mRecycle = (RecyclerView)findViewById(R.id.mRecycle);

        mMap = (ImageView)findViewById(R.id.mMap);
        mUser_name = (TextView)findViewById(R.id.mUser_name);
        actionA = (TextView) findViewById(R.id.action_a);
        actionB = (TextView) findViewById(R.id.action_b);
        actionC = (TextView) findViewById(R.id.action_c);
        actionD = (TextView) findViewById(R.id.action_d);
        actionE = (TextView) findViewById(R.id.action_e);
        actionHome = (TextView)findViewById(R.id.action_home);


        tv_signin=(TextView)findViewById(R.id.tv_signin);
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd  EEE");
        String str_Date=TimeUtils.getCurTimeString(sdf);
        tv_signin.setText("签到日期: "+str_Date);
        mainToolbar=(Toolbar)findViewById(R.id.mainToolbar);
        String user_name= App.getInstance().getUser(this).toString();
        mUser_name.setText(user_name);

        mainToolbar.inflateMenu(R.menu.menu_main);
        mainToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                int id=item.getItemId();
                if(id==R.id.action_settings){
                    toActivity(SettingActivity.class);
                }
                if(id==R.id.action_about){
                    toActivity(AboutActivity.class);
                }
                return false;
            }
        });

    }
    private void getHead(){
        //加载头像
        /*获得当前登录用户的用户名*/
        String user_name1=App.getInstance().getUser(MainActivity.this);
        HashMap<String, String> params = new HashMap<>();
        params.put("user_name",user_name1);
        JSONObject jsonObject = new JSONObject(params);
        OkGo.post(Api.GET_HEAD)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        hi = new HeadImage();
                        hi = JsonUtils.fromJson(s,HeadImage.class);
                        if (!(hi.getUrl().equals(" "))) {
                            Glide
                                    .with(MainActivity.this)
                                    .load(hi.getUrl())
                                    .placeholder(R.drawable.loading)
                                    .error(R.drawable.error)
                                    .dontAnimate()
                                    .into((ImageView) bigPic);
                        }

                    }
                });
    }

    private void initEvent(){

        /*侧边栏点击事件*/
        actionA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity(HolidayActivity.class);
            }
        });
        actionB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity(HolidayRecordActivity.class);
            }
        });
        actionC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity(SignInRecordActivity.class);
            }
        });
        actionD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity(UploadImageActivity.class);
            }
        });
        actionHome.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

            }
        });
        actionE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity(MessageActivity.class);
            }
        });


        //设置头像的点击事件
        findViewById(R.id.userInfo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity(UserActivity.class);

            }
        });



        mMap.setOnClickListener(new ImageView.OnClickListener(){

            @Override
            public void onClick(View v) {

                /**
                 * 在这里调用高德地图的接口，获取位置信息
                 * md.dismiss();可以关系提示框 根据需求关闭
                 */
                initLocation();
                mLocation.setText(location+"\n"+"经度："+Lon+"\n"+"纬度："+Lat);
                Log.v("zzz",mLocation.getText().toString());
                if (!(location == null)){
                    getTemp();
                }
            }
        });
    }

    /**
     * 签到的函数
     */
    private void getTemp(){
        //提示信息
        final MaterialDialog tt =new MaterialDialog.Builder(this)
                .title("提示")
                .content("获取签到信息中，请稍后...")
                .progress(true, 0)
                .show();
        /**
         * 获取需要签到的信息
         */
        OkGo.post(SIGNIN_MESSAGE)
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        tt.dismiss();
                        SighInMessage message = new SighInMessage();
                        message = JsonUtils.fromJson(s,SighInMessage.class);
                        //        final String[] temp = {"正常，<37.2°C",
//                                "低热，37.3°C~38°C",
//                                "中等热度，38.1°C~39°C",
//                                "高热，>39.1°C"};
                        final String[] temp = {message.getA(),message.getB(),message.getC(),message.getD()} ;

                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);


                        builder.setTitle("请选择你的体温：");//设置标题
                        builder.setIcon(android.R.drawable.ic_dialog_info);
                        builder.setSingleChoiceItems(temp,0,   //setSingleChoiceItems：就是单选
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which){
                                        picwhich = which;
                                    }});
                        //设置一个确定按钮
                        //final String text;
                        //text = msg;
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                uploadTemp = temp[picwhich];
                                dialog.dismiss();
                                SignIn();

                            }

                        });
                        builder.show();
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        Toast.makeText(MainActivity.this,"获取需要签到的信息失败",Toast.LENGTH_SHORT).show();
                        tt.dismiss();
                    }
                });

    }

    /*签到提示对话框*/
    public void signSuccess(String msg){
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("提示")
                .content(msg)
                .positiveText("确定")
                .show();

    }


    /*页面跳转*/
    public void toActivity(Class<?> clazz){
        Intent intent = new Intent(this,clazz);
        startActivity(intent);
    }
    /*显示正在加载对话框*/
    public void showWaitDialog(){
         /*显示提示正在签到对话框*/
         md=new MaterialDialog.Builder(this)
                .title("提示")
                .content("正在签到...")
                .progress(true, 0)
                .show();
    }

    public void SignIn(){
        showWaitDialog();
        /*获取当前时间*/
        java.text.SimpleDateFormat ss = new java.text.SimpleDateFormat("yyyy-MM-dd");
        String date= TimeUtils.getCurTimeString(ss);
        /*主要是为了拼凑unique_id*/
        java.text.SimpleDateFormat ss2 = new java.text.SimpleDateFormat("yyyyMMdd");

        String date2= TimeUtils.getCurTimeString(ss2);

        /*获得当前登录用户的用户名*/
        String user_name=App.getInstance().getUser(MainActivity.this);
         /*没人每天只有一个id*/
        String unique_id=user_name+date2;
        //经度转化为字符串
        strLon = String.valueOf(Lon);
        //纬度转化为字符串
        strLat = String.valueOf(Lat);

        /*构造请求体*/
        HashMap<String, String> params = new HashMap<>();
        params.put("unique_id", unique_id);
        //params.put("type", type);
        params.put("date", date);
        params.put("user_name",user_name);
        params.put("lon",strLon);
        params.put("lat",strLat);
        params.put("uploadMessage",uploadTemp);
        params.put("address",location);
        JSONObject jsonObject = new JSONObject(params);
     /*发送登录请求*/
        OkGo.post(Api.SIGNIN)//
                .tag(this)//
                .upJson(jsonObject.toString())//
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("Mainactivity____>", response.code()+"状态码："+call.toString() );
                        if(response.code()!=200){
                            /*打开签到成功提示对话框*/
                            signSuccess("后台维护中...");
                            return;
                        }
                        login=new ResponseLogin();
                        login= JsonUtils.fromJson(s,ResponseLogin.class);

                        if(login.getStatus().equals(Constant.SUCCESS)){
                            /*关闭加载对话框*/
                            md.dismiss();
                            /*打开签到成功提示对话框*/
                            signSuccess("签到成功");
                        }else if(login.getMsg().equals(Constant.ERROR_SYSTEM)){
                             /*关闭加载对话框*/
                            md.dismiss();
                            /*打开签到成功提示对话框*/
                            signSuccess("系统发生错误，请联系程序开发者");
                        }else if(login.getMsg().equals(Constant.ERROR_ALREADY_SIGNIN)){
                             /*关闭加载对话框*/
                            md.dismiss();
                            /*打开签到成功提示对话框*/
                            signSuccess("你已经签过了..请勿重复签！");
                        }else if(login.getMsg().equals("time_wrong")){
                            md.dismiss();
                            signSuccess("签到时间不正确！");
                        }
                    }
                });
    }
    /*双击退出程序*/
    @Override
    public void onBackPressed(){
        if(quit==false){//询问是否退出程序
            Toast.makeText(MainActivity.this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
            new Timer(true).schedule(new TimerTask() {
                @Override
                public void run() {
                    quit=false;
                }
            },2000);
            quit=true;
        }else {
            super.onBackPressed();
            finish();
        }
    }
}
